import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    rooms: [
      { number: '101', type: '标准间', price: '200', status: 'available' },
      { number: '102', type: '标准间', price: '200', status: 'available' },
      { number: '103', type: '标准间', price: '200', status: 'available' },
      { number: '104', type: '标准间', price: '200', status: 'available' },
      { number: '105', type: '标准间', price: '200', status: 'available' },
      { number: '201', type: '大床房', price: '300', status: 'available' },
      { number: '202', type: '大床房', price: '300', status: 'available' },
      { number: '203', type: '大床房', price: '300', status: 'available' },
      { number: '204', type: '大床房', price: '300', status: 'available' },
      { number: '205', type: '大床房', price: '300', status: 'available' },
      { number: '301', type: '豪华间', price: '500', status: 'available' },
      { number: '302', type: '豪华间', price: '500', status: 'available' },
      { number: '303', type: '豪华间', price: '500', status: 'available' },
      { number: '304', type: '豪华间', price: '500', status: 'available' },
      { number: '305', type: '豪华间', price: '500', status: 'available' }
    ],
    bookings: [],
    guests: [],
    totalIncome: 0,
    incomeRecords: [],
    serviceBookings: [] 
  },
  mutations: {
    ADD_BOOKING(state, booking) {
      state.bookings.push(booking)

      const room = state.rooms.find(r => r.number === booking.roomNumber)
      if (room) {
        room.status = 'occupied'
      }

      const existingGuest = state.guests.find(g => g.phone === booking.guestPhone)
      if (existingGuest) {
        existingGuest.name = booking.guestName
      } else {
        state.guests.push({
          name: booking.guestName,
          phone: booking.guestPhone,
          idCard: ''
        })
      }

      const checkInDate = new Date(booking.checkInDate)
      const checkOutDate = new Date(booking.checkOutDate)
      const diffTime = Math.abs(checkOutDate - checkInDate)
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

      const roomPrice = parseInt(room.price, 10)
      const income = roomPrice * diffDays
      state.totalIncome += income

      state.incomeRecords.push({
        date: new Date().toISOString().split('T')[0],
        type: '房费',
        amount: income,
        note: `房间 ${booking.roomNumber}，入住 ${booking.checkInDate} - ${booking.checkOutDate}`
      })
    },
    UPDATE_ROOM_STATUS(state, { roomNumber, status }) {
      const room = state.rooms.find(r => r.number === roomNumber)
      if (room) {
        room.status = status
      }
    },
    ADD_GUEST(state, guest) {
      state.guests.push(guest)
    },
    UPDATE_GUEST(state, { index, guest }) {
      state.guests.splice(index, 1, guest)
    },
    DELETE_GUEST(state, index) {
      state.guests.splice(index, 1)
    },
    DELETE_BOOKING(state, index) {
      const roomNumber = state.bookings[index].roomNumber
      const room = state.rooms.find(r => r.number === roomNumber)
      if (room) {
        room.status = 'available'
      }

      const booking = state.bookings[index]
      const checkInDate = new Date(booking.checkInDate)
      const checkOutDate = new Date(booking.checkOutDate)
      const diffTime = Math.abs(checkOutDate - checkInDate)
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

      state.bookings.splice(index, 1)

      const roomPrice = parseInt(room.price, 10)
      const income = roomPrice * diffDays
      state.totalIncome -= income

      const recordIndex = state.incomeRecords.findIndex(record => record.note.includes(`房间 ${roomNumber}`))
      if (recordIndex!== -1) {
        state.incomeRecords.splice(recordIndex, 1)
      }
    },
    ADD_SERVICE_TO_BOOKING(state, { booking, service }) {
      const servicePrice = parseInt(service.price, 10);
      state.totalIncome += servicePrice;
      state.incomeRecords.push({
        date: new Date().toISOString().split('T')[0],
        type: service.name,
        amount: servicePrice,
        note: `房间 ${booking.roomNumber}，客人 ${booking.guestName}，服务：${service.name}`
      });
      state.serviceBookings.push({
        booking,
        service
      });
    },
    DELETE_SERVICE_BOOKING(state, index) {
      const serviceBooking = state.serviceBookings[index];
      const servicePrice = parseInt(serviceBooking.service.price, 10);
      state.totalIncome -= servicePrice;
      const recordIndex = state.incomeRecords.findIndex(record => record.note.includes(`房间 ${serviceBooking.booking.roomNumber}`) && record.type === serviceBooking.service.name);
      if (recordIndex!== -1) {
        state.incomeRecords.splice(recordIndex, 1);
      }
      state.serviceBookings.splice(index, 1);
    }
  },
  actions: {
    addBooking({ commit }, booking) {
      commit('ADD_BOOKING', booking)
    },
    updateRoomStatus({ commit }, payload) {
      commit('UPDATE_ROOM_STATUS', payload)
    },
    addGuest({ commit }, guest) {
      commit('ADD_GUEST', guest)
    },
    updateGuest({ commit }, payload) {
      commit('UPDATE_GUEST', payload)
    },
    deleteGuest({ commit }, index) {
      commit('DELETE_GUEST', index)
    },
    deleteBooking({ commit }, index) {
      commit('DELETE_BOOKING', index)
    },
    addServiceToBooking({ commit }, payload) {
      commit('ADD_SERVICE_TO_BOOKING', payload);
    },
    deleteServiceBooking({ commit }, index) {
      commit('DELETE_SERVICE_BOOKING', index);
    }
  },
  getters: {
    availableRooms: state => state.rooms.filter(room => room.status === 'available'),
    occupiedRooms: state => state.rooms.filter(room => room.status === 'occupied'),
    allRooms: state => state.rooms,
    allGuests: state => state.guests,
    allBookings: state => state.bookings,
    totalIncome: state => state.totalIncome,
    incomeRecords: state => state.incomeRecords,
    serviceBookings: state => state.serviceBookings 
  }
})